# -*- coding: utf-8 -*-

import os
import cv2
import numpy

def getPatches(file_dir):
    images, labels = [], []
    fitable = []
    images_root, labels_root = '', ''
    for root, dirs, files in os.walk(file_dir):
        for file in files:
            file_name = os.path.splitext(file)[0]
            file_type = os.path.splitext(file)[1]
            if file_type == '.txt':
                labels.append(file_name)
                labels_root = root + '/'
            elif file_type == '.png':
                images.append(file_name)
                images_root = root + '/'
    fitable = list(set(images).intersection(set(labels)))
    return {'label':labels_root, 'image':images_root}, fitable
        
def loadLabels(label_file, match=''):
    label = []
    for line in open(label_file):
        if match and (match in line):
            label.append([int(num) for num in line.split()[0:8]])
    return label

def cutImage(image, size=416, stribe=208):
    height, width = image.shape[0] - 1, image.shape[1] - 1
    crops = []
    start_x, start_y = 0, 0
    end_x, end_y = size, size
    next_line = False
    while True:
        crops.append((start_x, start_y, end_x, end_y))

        if end_x == width and end_y == height: break

        if next_line:
            next_line = False
            start_y = start_y + stribe
            end_y = end_y + stribe
            if end_y > height:
                end_y = height
                start_y = end_y - size
            start_x = 0
            end_x = size
            continue

        end_x = end_x + stribe
        start_x = start_x + stribe
        if end_x > width:
            end_x = width
            start_x = end_x - size
            next_line = True    
    return crops
